package org.demo.localcache.guava;

import com.alibaba.fastjson.JSONObject;
import groovy.util.IFileNameFinder;
import lombok.extern.slf4j.Slf4j;
import org.demo.datasoureces.entity.UserInfo;
import org.demo.datasoureces.service.UserInfoService;
import org.demo.localcache.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Slf4j
@Service(value = "localDemoCache")
public class LocalDemoCache extends AbstractGuavaCache<String, User> implements ILocalCache<String,User>{
    @Value("${localcache.maximumSize:100}")
    private int maximumSize;

    @Value("${localcache.expire:10}")
    private int expireAfterDuration;

    @Autowired
    UserInfoService userInfoService;

    @PostConstruct
    public void init(){
        setMaximumSize(maximumSize);
        setExpireAfterDuration(expireAfterDuration);
        super.init();
    }

    @Override
    protected User fetchData(String key) {
        UserInfo userInfo= userInfoService.queryUserInfoById(3L);
        if (userInfo==null){ //判断获取数据是否为空，为空new一个空的user对象返回，防止缓存击穿
            return new User();
        }
        User user = new User();
        BeanUtils.copyProperties(userInfo,user);
        log.info("user is :"+ JSONObject.toJSONString(user));
        return user;
    }

    @Override
    public User get(String key) {
        try {
            return getValue(key);
        }catch (Exception e){
            log.error("LocalDemoCache exception:"+ e);
            return null;
        }
    }
}
